import {

    PageContainer,

} from '@ant-design/pro-components';
import { Button, Card, Col, Divider, Form, Input, InputNumber, message, Popconfirm, Radio, Row, Space, Tree, TreeDataNode, TreeProps } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { addApi, deleteApi, treeApi, flatApi, updateApi } from './services';




const Page: React.FC<unknown> = () => {
    const [currentItem, setCurrentItem] = useState<any>({})
    const [treeData, setTreeData] = useState<any[]>([])
    const [form] = Form.useForm();
    const [mode, setMode] = useState<"add" | "update">("add")

    const deleteItem = async (id: number) => {
        const res = await deleteApi(id)
        if (res.code == 200) {
            message.success("删除成功")
            getTree()
        }
    }
    useEffect(() => {
        getTree()
    }, [])


    const getTree = async () => {
        const res = await treeApi({ name: "一" });
        if (res.code == 200) {
            setTreeData(res.data)
        }
    }
    const onDragEnter: TreeProps['onDragEnter'] = (info) => {
        console.log(treeData);

    };

    const onDrop: TreeProps['onDrop'] = (info) => {
        // console.log(info);
        //@ts-ignore
        const dropKey = info.node.id;
        //@ts-ignore
        const dragKey = info.dragNode.id;
        const dropPos = info.node.pos.split('-');
        const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]); // the drop position relative to the drop node, inside 0, top -1, bottom 1

        const loop = (
            data: TreeDataNode[],
            id: React.Key,
            callback: (node: TreeDataNode, i: number, data: TreeDataNode[]) => void,
        ) => {
            for (let i = 0; i < data.length; i++) {
                //@ts-ignore
                if (data[i].id === id) {
                    return callback(data[i], i, data);
                }
                if (data[i].children) {
                    loop(data[i].children!, id, callback);
                }
            }
        };
        const data = [...treeData];

        // Find dragObject
        let dragObj: TreeDataNode;
        loop(data, dragKey, (item, index, arr) => {
            arr.splice(index, 1);
            dragObj = item;
        });

        if (!info.dropToGap) {
            // Drop on the content
            loop(data, dropKey, (item) => {
                item.children = item.children || [];
                // where to insert. New item was inserted to the start of the array in this example, but can be anywhere
                item.children.unshift(dragObj);
            });
        } else {
            let ar: TreeDataNode[] = [];
            let i: number;
            loop(data, dropKey, (_item, index, arr) => {
                ar = arr;
                i = index;
            });
            if (dropPosition === -1) {
                // Drop on the top of the drop node
                ar.splice(i!, 0, dragObj!);
            } else {
                // Drop on the bottom of the drop node
                ar.splice(i! + 1, 0, dragObj!);
            }
        }
        setTreeData(data);
    };
    const onFinish = async (values: any) => {
        if (mode == "add") {
            add(values)
        } else {
            update(values)
        }

    }

    const add = async (values: any) => {
        const hide = message.loading("正在提交！")
        const subData = {
            ...values
        }
        if (currentItem) {
            subData.parentId = currentItem.id;
        }
        const res = await addApi(subData)
        if (res.code == 200) {
            getTree()
            form.resetFields()
            message.success("提交成功！")
        }
        hide()
    }
    const update = async (values: any) => {
        const hide = message.loading("正在提交！")
        const subData = {
            ...currentItem,
            ...values
        }

        const res = await updateApi(subData)
        if (res.code == 200) {
            getTree()
            setCurrentItem(subData);
            form.resetFields()
            message.success("提交成功！")
        }
        hide()
    }

    const treeSelect = (selectedKeys: any, e: any) => {
        console.log(selectedKeys, e);
        const node = e.node;
        setMode("add")
        setCurrentItem({
            id: node.id,
            name: node.name,
            sort: node.sort,
            path: node.path,
            parentId: node.parentId,
        })
        form.resetFields()


    }
    const treeRightClick = (e: any) => {
        console.log(e)
    }
    const modeChange = (e: any) => {
        setMode(e.target.value);
        if (e.target.value == "add") {
            form.resetFields()
        } else {
            form.setFieldsValue({
                name: currentItem.name,
                sort: currentItem.sort,
                path: currentItem.path
            })
        }
    }
    const deleteClick = async () => {
        if (!currentItem.id) {
            message.error("请先选择菜单！")
            return
        }
        const hide = message.loading("正在删除")
        const res = await deleteApi(currentItem.id);
        if (res.code == 200) {
            message.success("删除成功！")
            form.resetFields();
            setCurrentItem({})
        }   getTree()
        hide()
    }
    return (
        <PageContainer
            header={{
                title: '菜单设置',
            }}
        >
            <Card>
                <Row>
                    <Col span={8}>
                        <Button type="primary" onClick={() => { setCurrentItem({}); form.resetFields() }}>创建根菜单</Button>
                        <div style={{ height: "20px" }}></div>
                        {treeData.length > 0 && <Tree
                            // showLine={true}
                            defaultExpandAll={true}
                            className="draggable-tree"
                            // defaultExpandedKeys={expandedKeys}
                            draggable
                            blockNode
                            onDragEnter={onDragEnter}
                            onDrop={onDrop}
                            treeData={treeData}
                            fieldNames={{
                                title: "name",
                                key: "id",
                                children: "children"
                            }}
                            onSelect={treeSelect}
                            onRightClick={treeRightClick}
                        />}
                    </Col>
                    <Col span={12}>

                        <Form
                            form={form}
                            onFinish={onFinish}
                            labelCol={{ span: 6 }}
                            wrapperCol={{ span: 14 }}

                        >


                            <Row>
                                <Col span={18}>
                                    <Form.Item
                                        label="当前菜单"

                                    >
                                        {currentItem.name}
                                    </Form.Item>
                                    <Form.Item
                                        label="路径"

                                    >
                                        {currentItem.path}
                                    </Form.Item>
                                </Col>
                                <Col span={6}>
                                    <Popconfirm
                                        title="删除"
                                        description="确认删除当前菜单？"
                                        onConfirm={deleteClick}
                                    >
                                        <Button danger >删除</Button>
                                    </Popconfirm>



                                </Col>
                            </Row>
                            <Radio.Group
                                name="radiogroup"
                                onChange={modeChange}
                                value={mode}
                                options={[
                                    { value: 'add', label: '新增子菜单' },
                                    { value: "update", label: '更新当前' },
                                ]}
                            />

                            <Divider>菜单填写</Divider>
                            {/* 分类名称 */}
                            <Form.Item
                                label="菜单名称"
                                name="name"
                                rules={[
                                    { required: true, message: '请输入名称' },
                                ]}
                            >
                                <Input />
                            </Form.Item>

                            {/* 路径 */}
                            <Form.Item
                                label="路径"
                                name="path"

                            >
                                <Input />
                            </Form.Item>

                            {/* 排序 */}
                            <Form.Item
                                label="排序"
                                name="sort"
                                initialValue={0}
                            >
                                <InputNumber min={0} style={{ width: '100%' }} />
                            </Form.Item>



                            <Form.Item wrapperCol={{ offset: 6, span: 14 }}>
                                <Space>
                                    <Button type="primary" htmlType="submit">
                                        提交
                                    </Button>

                                </Space>
                            </Form.Item>



                        </Form>




                    </Col>


                </Row>
            </Card>
        </PageContainer>
    );
};

export default Page;
